﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Wireless;
using Microsoft.Win32;

namespace GoogleVoice
{
    /// <summary>
    /// The main stuff for making calls through Google Voice.
    /// </summary>
    public partial class DialPad : Form
    {
        String destNumber = "";
        String myNumber = "";
        String username;
        String password;
        Settings settings;
        OutlookSession outlook = new OutlookSession();
        /// <summary>
        /// Loads the widgets and the contacts from Outlook, as well as the registry values.
        /// </summary>
        public DialPad()
        {
            InitializeComponent();
            //item.FirstName.Contains("A")
            var query = from Contact item in outlook.Contacts.Items where true select item;
            this.contactName.BeginUpdate();
            foreach(var item in query){
                this.contactName.Items.Add(item.FileAs);
            }
            this.contactName.EndUpdate();
            this.LoadSettings(null, null);
        }
        /// <summary>
        /// Did you press a button? This is how the number is dialed and added to the call box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DialButton(object sender, EventArgs e)
        {
            Button key = (Button)sender;
            String num = key.Text.Substring(0,1);
            this.destNumber += num;
            this.FormatNum(null, null);
        }

        /// <summary>
        /// Removes the last dialed number from the call box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DialBack(object sender, EventArgs e)
        {
            if (this.destNum.Text.Length == 0) return;
            this.destNumber = this.destNumber.Substring(0, this.destNumber.Length - 1);
            this.FormatNum(null, null);
        }

        /// <summary>
        /// Connects the call.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConnectCall(object sender, EventArgs e)
        {
            if (this.destNumber.Length != 10)
            {
                MessageBox.Show("Please enter a valid number to call box.");
                return;
            }
            try
            {
                if(this.myNumber.Length != 10)
                    this.myNumber = Sim.GetPhoneNumber().Address;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please enter a valid number to connect to in the settings.");
                return;
            }
            String url = String.Format(@"{0}/{1}/{2}", Constants.gvPHP, this.destNumber, this.myNumber);
            WebRequest req = WebRequest.Create(url);
            {
                try
                {
                    Stream res = req.GetResponse().GetResponseStream();
                    StreamReader resReader = new StreamReader(res);
                    string resText = resReader.ReadToEnd();
                    if (resText.Contains("200"))
                    {
                        notification.Text = String.Format("Calling you at <b>{0}</b>...",PhoneUtils.FormatPhoneText(this.myNumber));
                        notification.Visible = true;
                    }
                    else
                    {
                        notification.Critical = true;
                        notification.Text = "Problem connecting call.";
                        notification.Visible = true;
                    }
                }
                catch (WebException ex)
                {
                    MessageBox.Show("Network error: Couldn't connect.", "GoogleVoice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
            } 
        }
        /// <summary>
        /// Called to format the phone text when the Back button is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormatNum(object sender, EventArgs e)
        {
            this.destNum.Text = PhoneUtils.FormatPhoneText(this.destNumber);
        }
        /// <summary>
        /// When a Contact has been selected, it loads the available numbers into the call type box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContactSelect(object sender, EventArgs e)
        {
            int index = this.contactName.SelectedIndex;
            Contact contact = outlook.Contacts.Items[index];
            this.contactType.BeginUpdate();
            this.contactType.Items.Clear();
            if (contact.HomeTelephoneNumber.Length > 0)
                this.contactType.Items.Add("H");
            if (contact.MobileTelephoneNumber.Length > 0)
                this.contactType.Items.Add("M");
            if (contact.BusinessTelephoneNumber.Length > 0)
                this.contactType.Items.Add("W");
            this.contactType.EndUpdate();
        }
        /// <summary>
        /// When the type of number for the contact has been selected, it loads the number into the call box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContactTypeSelect(object sender, EventArgs e)
        {
            int index = this.contactName.SelectedIndex;
            Contact contact = outlook.Contacts.Items[index];
            String val = this.contactType.Text;
            String num = "";
            if ("H" == val)
                 num = contact.HomeTelephoneNumber;
            else if ("M" == val)
                num = contact.MobileTelephoneNumber;
            else if ("W" == val)
                num = contact.BusinessTelephoneNumber;
            this.destNumber = PhoneUtils.CleanPhoneText(num);
            this.destNum.Text = this.destNumber;
        }
        /// <summary>
        /// Hides the notification icon in the system tray.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotificationChanged(object sender, Microsoft.WindowsCE.Forms.BalloonChangedEventArgs e)
        {
            if (e.Visible == false)
            {
                notification.Visible = false;
            }
        }
        /// <summary>
        /// Load a modal Settings window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LaunchSettings(object sender, EventArgs e)
        {
            this.settings = new Settings();
            this.settings.Closed += new EventHandler(LoadSettings);
            this.settings.ShowDialog();
        }
        /// <summary>
        /// Load the settings from the Registry.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void LoadSettings(object sender, EventArgs e)
        {
            this.username = (String)Registry.GetValue(Constants.REG_PATH, "gvUsername", "");
            this.password = (String)Registry.GetValue(Constants.REG_PATH, "gvPassword", "");
            this.myNumber = (String)Registry.GetValue(Constants.REG_PATH, "gvMyNumber", "");
        }
        /// <summary>
        /// Quit the program.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QuitClick(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}